import React from 'react'
import { connect } from 'react-redux'
import { Button, Table, Badge, Form, message, Input, Modal, Alert, Switch} from 'antd';
const FormItem = Form.Item;
import {messages} from "share/common";
import SearchArea from 'components/search-area'
import 'styles/setting/company-level-define/company-level-define.scss'
import LanguageInput from 'components/template/language-input/language-input'
import CompanyLevelDefineService from 'containers/setting/company-level-define/company-level-define.service'
import ResizeTable from "components/resize-table";

class CompanyLevelDefine extends React.Component {
  constructor (props){
    super (props);
    this.state = ({
      loading: false,
      data: [],
      page: 0,
      pageSize: 10,
      pagination: {total: 0},
      visible: false,
      record: {
        id: null,
        enabled: true,
        companyLevelCode: '',
        description: '',
        i18n: {
          description: [],
        }
      },
      searchParams: {
        companyLevelCode: '',
        description: ''
      },
      searchForm: [
        {type: 'input', id: 'companyLevelCode', label: messages('setting.key259'/*公司级别代码*/)},
        {type: 'input', id: 'companyLevelDescription', label: messages('setting.key186'/*描述*/),},
      ],
      columns: [
        {title: messages('setting.key259'/*公司级别代码*/), key: 'companyLevelCode', dataIndex: 'companyLevelCode'},
        {title: messages('setting.key186'/*描述*/), key: 'description', dataIndex: 'description'},
        {title: messages("common.column.status")/*状态*/, key: 'enabled', dataIndex: 'enabled', render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages("common.status.enable") : messages("common.status.disable")} />)},
      ],
    })
  }
  componentWillMount () {
    this.getList ();
  }

  //得到列表数据
  getList = () => {
    const {searchParams, page, pageSize} = this.state;
    this.setState({loading: true});
    let params = searchParams;
    params.page = page;
    params.size = pageSize;
    CompanyLevelDefineService.getList(params).then(response => {
      this.setState({
        data: response.data,
        loading: false,
        pagination: {
          total: Number(response.headers['x-total-count']),
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    }).catch(err => {

    });
  };

  //分页点击
  onChangePager = (page) => {
    if(page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, ()=>{
        this.getList();
      })
  };

  //点击搜索
  onSearch = (result) => {
    const {pageSize} = this.state;
    this.setState({
      page: 0,
      searchParams: Object.assign({}, this.state.searchParams, result),
      loading: true,
    }, () => {
      let companyLevelCode = this.state.searchParams.companyLevelCode ? this.state.searchParams.companyLevelCode : '';
      let description = this.state.searchParams.companyLevelDescription ? this.state.searchParams.companyLevelDescription : '';
      let item = {
        companyLevelCode,
        description: description,
        page: this.state.page,
        pageSize: pageSize,
      };
      CompanyLevelDefineService.onSearch(item).then(res => {
        this.setState({
          data: res.data,
          loading: false,
          pagination: {
            total: Number(res.headers['x-total-count']),
            onChange: this.onChangePager,
            current: this.state.page + 1
          }
        })
      }).catch(err => {

      });
    })
  };

  //点击重置
  onSearchClear = () => {
    this.setState({
      searchParams: {
        companyLevelCode: '',
        description: ''
      }
    }, () => {
      this.getList ();
    })
  };

  //点击新建
  newCompanyLevel = () => {
    this.setState({
      record: {
        id: null,
        enabled: true,
        companyLevelCode: '',
        description: '',
        i18n: {
          description: [],
        }
      },
      visible: true,
    })
  };

  //公司级别描述多语言
  handlePeriodSetNameChange = (value, i18n) => {
    const {record} = this.state;
    record.i18n.description = i18n;
    record.description = value;
    this.setState({ record })
  };

  //点击table某一行数据
  handleRowClick = (record) => {
    this.setState({
      record: record,
      visible: true,
    })
  };

  //点击模态框的确定
  handleModalOk = () => {
    const {record} = this.state;
    this.props.form.validateFieldsAndScroll((errs, values) => {
      if(!errs){
        this.setState({
          loading: true,
        });
        let params = Object.assign(record, values);
        CompanyLevelDefineService.newEditRecord(params).then(res => {
          message.success(messages('setting.key211'/*保存成功*/));
          this.setState({
            visible: false,
            loading: false,
            record: {
              id: null,
              enabled: true,
              companyLevelCode: '',
              description: '',
              i18n: {
                description: [],
              }
            }
          });
          this.getList();
        }).catch(err => {
          this.setState({
            loading: false,
          });
        });
      }
    })
  };

  //点击模态框的取消
  onModalCancel = () => {
    this.props.form.resetFields();
    this.setState({
      visible: false,
      record: {
        id: null,
        enabled: true,
        companyLevelCode: '',
        description: '',
        i18n: {
          description: [],
        }
      }
    });
    this.getList();
  };

  render () {
    const {getFieldDecorator} = this.props.form;
    const {searchForm, columns, data, pagination, visible, loading, record} = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1},
    };
    return (
      <div>
        <SearchArea searchForm={searchForm}
                    clearText={messages('common.reset')/*重置*/}
                    submitHandle={this.onSearch}
                    clearHandle={this.onSearchClear}/>
        <div style={{marginTop: 30}}>
          <div style={{margin: '10px 0'}}>
            <Button type='primary'
                    disabled={!this.props.tenantMode}
                    onClick={this.newCompanyLevel}>
              {messages("common.create")/*新建*/}
            </Button>
          </div>
          <div>
            <div style={{margin: '10px 0', fontSize: 13 }}>
              {messages("common.total", {total: pagination.total})/*{`共搜索到${data.length}条数据`}*/}
            </div>
            <ResizeTable
              rowKey={'id'}
              size="middle"
              dataSource={data}
              columns={columns}
              loading={loading}
              pagination={pagination}
              onRow={record => ({onClick: () => this.handleRowClick(record)})}
              bordered
            />
          </div>
        </div>
        <Modal visible={visible}
               title={ record.id ? messages('setting.key266'/*编辑公司级别定义*/) :messages('setting.key263'/*新增公司级别定义*/)}
               onOk={this.handleModalOk}
               onCancel={this.onModalCancel}
               confirmLoading={loading}
               afterClose={() => {this.props.form.resetFields()}}>
          <Alert
            type="info"
            style={{marginBottom : 16}}
            message={messages("common.help")/*帮助提示*/}
            description={messages('setting.key264'/*【公司级别代码】 保存后将不可修改*/)}
            showIcon
          />
          <Form>
            <FormItem label={messages("common.column.status")/*状态*/} {...formItemLayout}>
              {getFieldDecorator('enabled', {
                rules: [{
                  required: false,
                }],
                initialValue: record.enabled,
                valuePropName: 'checked',
              })(
                <Switch/>
              )}
            </FormItem>
            <FormItem label={messages('setting.key259'/*公司级别代码*/)} {...formItemLayout}>
              {getFieldDecorator('companyLevelCode', {
                rules: [{
                  required: true,
                  message: messages('setting.key265'/*公司级别代码不能为空*/)
                }],
                initialValue: record.companyLevelCode,
              })(
                <Input  disabled={!this.props.tenantMode || record.id}
                        placeholder={messages('common.please.enter')/*请输入*/}/>
              )}
            </FormItem>
            <FormItem label={<span><span className='default-color-inverse-font'>*</span>&nbsp;{messages('components.key12'/*描述*/)}</span>} {...formItemLayout}>
              <LanguageInput name={record.description ? record.description : ''}
                             isEdit={record.id}
                             disabled={!this.props.tenantMode}
                             i18nName={record.i18n && record.i18n.description}
                             nameChange={this.handlePeriodSetNameChange}/>
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
}
CompanyLevelDefine.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
  }
}

const wrappedNewContract = Form.create()(CompanyLevelDefine);
export default connect(mapStateToProps)(wrappedNewContract);
